package io.dcloud.uniplugin;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolInstance {
    private static ThreadPoolInstance INSTANCE = null;
    private ExecutorService singleThreadExecutor = null;
    private ExecutorService fixedThreadPool = null;
    private ThreadPoolExecutor threadPoolExecutor = null;

    public static ThreadPoolInstance getInstance() {
        synchronized (ThreadPoolInstance.class) {
            if (INSTANCE == null) {
                INSTANCE = new ThreadPoolInstance();
            }
        }
        return INSTANCE;
    }

    /**
     * 获取基本线程池
     * keepAliveTime设置为0，非核心线程空闲时会被立即回收
     */
    public ThreadPoolExecutor getThreadPoolExecutor() {
        synchronized (ThreadPoolInstance.class) {
            if (threadPoolExecutor == null) {
                threadPoolExecutor = new ThreadPoolExecutor(5, 10, 0, TimeUnit.SECONDS, new LinkedBlockingQueue(Integer.MAX_VALUE));
            }
        }
        return threadPoolExecutor;
    }

    /**
     * 获取单线程池
     */
    private ExecutorService getSingleThreadExecutor() {
        synchronized (ThreadPoolInstance.class) {
            if (singleThreadExecutor == null) {
                singleThreadExecutor = Executors.newSingleThreadExecutor();
            }
        }
        return singleThreadExecutor;
    }

    /**
     * 获取固定核心数线程池
     */
    private ExecutorService getFixedThreadPool() {
        synchronized (ThreadPoolInstance.class) {
            if (fixedThreadPool == null) {
                fixedThreadPool = Executors.newFixedThreadPool(5);
            }
        }
        return fixedThreadPool;
    }
}
